/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.imsx.controller;

import com.imsx.controller.util.Driver;
import com.imsx.model.Producto;
import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import org.bson.types.ObjectId;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.event.ActionEvent;

/**
 *
 * @author mivkys
 */
@ManagedBean(name = "productoController")
@SessionScoped
public class ProductoController {
    private Map<String, Producto> items;
    private Producto selected;
    private DB dB;
    private Driver driver;

    public ProductoController() {
    }
    @PostConstruct
    public void init() {
        try {
            dB = new Mongo().getDB("amazondb");
        } catch (UnknownHostException ex) {
            Logger.getLogger(OrdenController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MongoException ex) {
            Logger.getLogger(OrdenController.class.getName()).log(Level.SEVERE, null, ex);
        }
        selected = new Producto();
        items = new HashMap<>();
        
        Driver.findProducto(dB, null, items);// cargar todos los productos
    }
    public void prepareCreateItem(ActionEvent event) {// cuando seleccionamos un producto

        selected = new Producto();
        
    }
    public void create(ActionEvent event){
        selected.setProductoId(new ObjectId().toString());
        ArrayList<Object> productos = new ArrayList<Object>();
                productos.add(selected);
        try {
            Driver.insert(productos, dB.getCollection("producto"));
        } catch (IOException ex) {
            Logger.getLogger(ProductoController.class.getName()).log(Level.SEVERE, null, ex);
        }
        selected = null;
    }
    public List<Producto> getItems(){
        List<Producto> targetList = new ArrayList<>(items.values());
        return targetList;
    }
    public void setItems(List<Producto> items){
      for (Producto item : items) {
            this.items.put(item.getProductoId(), item);
        }
    }

    public Producto getSelected() {
        return selected;
    }

    public void setSelected(Producto selected) {
        this.selected = selected;
    }
   
}
